package com.itheima.controller;

import com.itheima.Pojo.AliyunOSSProperties;
import com.itheima.Pojo.Result;
import com.itheima.utils.AliyunOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadControl {
//    /**
//     *文件上传------本地存储
//     * @param username
//     * @param age
//     * @param file
//     * @return
//     */
//    @PostMapping("/upload")
//    public Result upload(String username, Integer age, MultipartFile file) throws Exception {
//
//        //获取原始文件名
//        String originalFilename = file.getOriginalFilename();
//
//        // 通过UUID随机生成字符串
//        String newFileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//
//        //将前端上传的文件存储到本地
//        file.transferTo(new File("D:/"+newFileName));
//
//        return  Result.success(newFileName);
//    }
//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint;
//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName;
    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;
    /**
     * 阿里云oss----文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {

        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String extName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //调用阿里云oss工具类，将文件上传到oss
        String url = AliyunOSSUtils.upload(aliyunOSSProperties.getEndpoint(), aliyunOSSProperties.getBucketName(), file.getBytes(), extName);

        return  Result.success(url);
    }
}
